<template>
  <div class="app-container">
    <el-table
      v-loading="loading"
      :data="suppliersList"
      @selection-change="handleSelectionChange"
      :default-sort = "{prop: 'date', order: 'descending'}"
    >
      <!-- <el-table-column type="编号" width="55" align="center" /> -->
      <el-table-column label="项目编号" align="center" prop="projectId" sortable />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column
        label="立项日期"
        align="center"
        prop="establishmentDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.establishmentDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="过审金额" align="center" prop="invoiceAmount" />
      <el-table-column label="已支付金额" align="center" prop="paidAmount" />
      <el-table-column label="负责人" align="center" prop="projectLeader" />
      <el-table-column
        label="是否完成"
        align="center"
        prop="isProjectCompleted"
      />
      <el-table-column label="操作人" align="center" prop="whiteListOperator" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            >查看详情</el-button
          >
          <!-- v-if="Number(scope.row.totalAmount) > Number(scope.row.invoiceAmount)" -->
          <el-button
            size="mini"
            type="text"
            v-if="Number(scope.row.paidAmount) !=  Number(scope.row.invoiceAmount)"
            @click="
              () => {
                payOpen = true;
                payReimbursementList = scope.row;
                payReimbursementList.allowablePayment =
                  scope.row.totalAmount - scope.row.paidAmount;
              }
            "
            >支付</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改供应商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body >
      <el-table v-loading="loading" :data="payReimbursementList">
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="实际金额" align="center" prop="actualPrice" />
        <el-table-column
          label="付款日期"
          align="center"
          prop="paymentDate"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.paymentDate, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="付款金额" align="center" prop="paymentAmount" />
        <el-table-column label="发票情况" align="center" prop="invoiceStatus" />
        <!-- <el-table-column label="发票" align="center" prop="uploadedInvoice" /> -->
        <el-table-column
          label="报销/付款日期"
          align="center"
          prop="createTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.createTime, "{y}-{m}-{d}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="立项编号" align="center" prop="initiationId" />
        <el-table-column
          label="供应商名"
          align="center"
          prop="purchaseTableSequence"
        />
        <el-table-column
          label="是否增项"
          align="center"
          prop="isAdditionalItem"
        />
        <el-table-column label="经办人" align="center" prop="filler" />
        <el-table-column label="类型" align="center" prop="type" />
        <!-- <el-table-column label="发票金额" align="center" prop="invoicePrice" /> -->
      </el-table>

      <div>付款明细</div>
      <el-table v-loading="loading" :data="paySums">
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="供应商名" align="center" prop="supplierId" />
        <el-table-column
          label="付款日期"
          align="center"
          prop="createdDate"
          width="180"/>
        <el-table-column label="付款金额" align="center" prop="paymentAmount" />
      </el-table>
    </el-dialog>

    <!-- 支付弹出层 -->
    <el-dialog
      :title="title"
      :visible.sync="payOpen"
      width="50%"
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="总额">
          {{ payReimbursementList.totalAmount }}
        </el-form-item>
        <el-form-item label="发票金额">
          {{ payReimbursementList.invoiceAmount || '未定义' }}
        </el-form-item>
        <el-form-item label="付款金额">
          <el-input
            v-model="payReimbursementList.paymentAmount"
            @input="handleInputPaymentAmount"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="payOpen = false">取 消</el-button>
        <el-button type="primary" @click="handlePay(payReimbursementList)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSuppliers,
  getSuppliers,
  delSuppliers,
  addSuppliers,
  updateSuppliers,
  getPayableSummary,
  setPayableSummary,
  setPayable,
} from "@/api/vendor/suppliers";

export default {
  name: "Suppliers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商表格数据
      suppliersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
        categoryName: null,
        supplierName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "供应商类型不能为空", trigger: "change" },
        ],
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" },
        ],
      },
      payReimbursementList: [],
      payOpen: false,
      paySums: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询供应商列表 */
    getList() {
      this.loading = true;
      getPayableSummary().then((response) => {
        this.suppliersList = (response.data || []).filter(item => item.isnumber1 === "1");
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        supplierId: null,
        categoryName: null,
        supplierName: null,
        supplierIntroduction: null,
        contactPerson: null,
        contactPhone: null,
        address: null,
        creationTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.supplierId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.supplierId != null) {
            updateSuppliers(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSuppliers(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const supplierIds = row.supplierId || this.ids;
      this.$modal
        .confirm('是否确认删除供应商编号为"' + supplierIds + '"的数据项？')
        .then(function () {
          return delSuppliers(supplierIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/suppliers/export",
        {
          ...this.queryParams,
        },
        `suppliers_${new Date().getTime()}.xlsx`
      );
    },
    handleDetail(row) {
      console.log("支付", row);
      setPayableSummary(row.initiationId, row.supplierName).then(
        (response) => {
          console.log("报销应付数据：", response.oaOtheraPurchases);
          this.payReimbursementList = response.oaOtheraPurchases;
          this.paySums = response.oaPaySums;
          this.open = true;
          this.title = "报销应付";
        }
      );
    },
    handlePay(row) {
      console.log("支付", row);
      let payData = {
        initiationId: this.payReimbursementList.initiationId,
        supplierId: this.payReimbursementList.supplierName,
        totalAmount: this.payReimbursementList.totalAmount,
        createdDate: this.payReimbursementList.establishmentDate,
        paymentAmount: this.payReimbursementList.paymentAmount,
        paybleSummaryId: this.payReimbursementList.oaSupplierPayableSummary.id,
        allowablePayment: this.payReimbursementList.invoiceAmount,
      };
      setPayable(payData).then((response) => {
        console.log("支付成功", response);
        this.$modal.msgSuccess("支付成功");
        this.payOpen = false;
        this.getList();
      });
    },
    handleInputPaymentAmount(e) {
      const value = e;
      if (value > this.payReimbursementList.oaSupplierPayableSummary.settlementAmount) {
        this.$modal.msgError("付款金额不能大于发票金额");
        this.payReimbursementList.paymentAmount =
        this.payReimbursementList.oaSupplierPayableSummary.settlementAmount;
      }
    },
  },
};
</script>
